// Eternal Lands Bot
// Copyright (C) 2006  Artem Makhutov
// artem@makhutov.org
// 
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

using System;
using System.Timers;

namespace cs_elbot.AdvancedCommunication
{
    /// <summary>
    /// description of AdvertHandler.
    /// </summary>
    public class AdvertHandler
    {
        private TCPWrapper TheTCPWrapper;
        private MySqlManager TheMySqlManager;
        private Logger TheLogger;
        private TradeHandler TheTradeHandler;
        private Inventory TheInventory;
        private System.Timers.Timer AdvertTimer = new System.Timers.Timer();
        //private System.Timers.Timer AdvertTimer2 = new System.Timers.Timer();

        //private int Channel = 3;

        public AdvertHandler(TCPWrapper MyTCPWrapper, MySqlManager MyMySqlManager, Logger MyLogger, TradeHandler MyTradeHandler, Inventory MyInventory)
        {
            Random RandomClass = new Random();
            int i;
            this.TheLogger = MyLogger;
            this.TheMySqlManager = MyMySqlManager;
            this.TheTCPWrapper = MyTCPWrapper;
            this.TheTradeHandler = MyTradeHandler;
            this.TheInventory = MyInventory;

            TheTCPWrapper = MyTCPWrapper;
            TheMySqlManager = MyMySqlManager;
            if (TheMySqlManager.advertchannel(Settings.botid) < 32768)
            {
                if (TheMySqlManager.lastadverttime(Settings.botid) > TheMySqlManager.minadverttime())
                    this.AdvertTimer.Interval = 1000;
                else
                {
                    i = TheMySqlManager.minadverttime() * 1000;
                    i += (RandomClass.Next(0, TheMySqlManager.randomadvertdelay()) * 1000);
                    if (i < 900000)
                        i = 900000;//minimum 15 minute delay
                    this.AdvertTimer.Interval = i;
                }
            }
            else
            {
                this.AdvertTimer.Interval = 1000;
            }
            //this.AdvertTimer2.Interval = (61*1000);//m*s*us=1 hour
            //AdvertTimer2.Elapsed += new ElapsedEventHandler(AdvertTimer2_Tick);

            TheLogger.Debug("New AdvertTimer.Interval: " + this.AdvertTimer.Interval + "\n");

            AdvertTimer.Elapsed += new ElapsedEventHandler(AdvertTimer_Tick);
            TheTCPWrapper.GotConnected += new TCPWrapper.GotConnectedEventHandler(OnGotConnected);
            TheTCPWrapper.GotDisconnected += new TCPWrapper.GotDisconnectedEventHandler(OnGotDisconnected);
        }

        private void AdvertTimer_Tick(object sender, ElapsedEventArgs e)
        {
            //int Channel = 32768;
            int i = 0, RandomAdvertNumber, ii;
            Random RandomClass = new Random();
            string str = "", str2 = "", endm = TheMySqlManager.advertendmessage().Trim();
            if (TheTradeHandler.AmITrading() || (TheInventory.GettingInventoryItems == true))
            {
                this.AdvertTimer.Interval = (1 * 1000);// +RandomClass.Next(0, (60 * 60 * 1000)); ;//m*s*us=1 hour
                TheLogger.Debug("Advert delayed due to current trade\n");
                return;
            }
            if (TheMySqlManager.advertchannel(Settings.botid) != 99999999)
            {
                //this.AdvertTimer.Interval = (15 * 60 * 1000) + RandomClass.Next(0, (60 * 60 * 1000)); ;//m*s*us=1 hour
                //this.AdvertTimer.Interval=60*

                i = TheMySqlManager.minadverttime() * 1000;
                i += (RandomClass.Next(0, TheMySqlManager.randomadvertdelay()) * 1000);
                if (i < 900000)
                    i = 900000;//minimum 15 minute delay
                this.AdvertTimer.Interval = i;
            }
            else
            {
                this.AdvertTimer.Interval = 1000;
            }
            TheLogger.Debug("New AdvertTimer.Interval: " + this.AdvertTimer.Interval + "\n");

            if (TheMySqlManager.advertchannel(Settings.botid) != 99999999 && TheMySqlManager.lastadverttime(Settings.botid) < TheMySqlManager.minadverttime() && MainClass.serverName != "test")
                return;
            if (TheMySqlManager.advertise())
            {
                System.Collections.ArrayList MyInventoryList = TheInventory.GetInventoryList();
                System.Collections.Hashtable MySellingItemsList = TheMySqlManager.GetSellingItemList(1);

                // sum up all inventory items if the items are on sale
                System.Collections.SortedList TheInventoryList = new System.Collections.SortedList();
                System.Collections.Hashtable MyWantedItemsList = TheMySqlManager.GetWantedItemList(1);

                foreach (Inventory.inventory_item MyInventoryItem in MyInventoryList)
                {
                    if (MySellingItemsList.Contains(MyInventoryItem.SqlID))
                    {
                        if (TheInventoryList.Contains(MyInventoryItem.SqlID) && MyInventoryItem.pos < 36)
                        {
                            Inventory.inventory_item TempInventoryItem = (Inventory.inventory_item)TheInventoryList[MyInventoryItem.SqlID];
                            TempInventoryItem.quantity += MyInventoryItem.quantity;
                            TheInventoryList[MyInventoryItem.SqlID] = TempInventoryItem;
                        }
                        else
                        {
                            if (MyInventoryItem.pos < 36)
                            {
                                TheInventoryList.Add(MyInventoryItem.SqlID, MyInventoryItem);
                            }
                        }
                    }
                }
                foreach (Inventory.inventory_item MyInventoryItem in TheInventoryList.Values)
                {
                    if (RandomClass.Next(0, 36) > 28 && MyInventoryItem.pos < 36)
                    {
                        TradeHandler.SellingItem MySellingItem = (TradeHandler.SellingItem)(MySellingItemsList[MyInventoryItem.SqlID]);
                        if (MySellingItem.pricesale > 0)
                        {
                            uint tempAmount = 0;
                            if ((TheMySqlManager.ReservedAmount(MyInventoryItem.SqlID)) < MyInventoryItem.quantity)
                            {
                                tempAmount = MyInventoryItem.quantity;
                                tempAmount = tempAmount - (TheMySqlManager.ReservedAmount(MyInventoryItem.SqlID));
                            }
                            else
                            {
                                continue;
                            }
                            str2 = tempAmount.ToString() + " " + MyInventoryItem.name + ":" + MySellingItem.pricesale.ToString() + "gc";
                            if (str.Length + str2.Length + endm.Length < 140)
                            {
                                if (!str.Contains(str2))
                                {
                                    if (str.Length > 0)
                                        str += ", ";
                                    str += str2;
                                }
                            }
                        }
                    }
                }
                if (str != "")
                {
                    //str2 = "Selling: " + str.Substring(0,str.Length-2) + endm;
                    str2 = "Selling: " + str + ". ";
                    str = str2;
                }
                string buylist = "Buying:";
                foreach (TradeHandler.WantedItem MyWantedItem in MyWantedItemsList.Values)
                {
                    if (RandomClass.Next(0, 36) > 28)
                    {
                        if (MyWantedItem.pricepurchase > 0)
                        {
                            str2 = TheMySqlManager.GetKnownItemsname(MyWantedItem.KnownItemsSqlID) + ":" + MyWantedItem.pricepurchase.ToString() + "gc";
                            if (str.Length + str2.Length + buylist.Length + endm.Length < 140)
                            {
                                if (buylist.Length > 7)
                                    buylist += ", ";
                                buylist += str2;
                            }
                        }
                    }
                }
                if (buylist.Length > 7)
                    str += buylist + ". ";
                if (str.Length > 0)
                    str += endm;
                if (str == "")
                {
                    try
                    {
                        System.Collections.ArrayList AdvertsArrayList = TheMySqlManager.GetBotAdverts(Settings.botid);

                        if (AdvertsArrayList.Count > 0)
                        {
                            RandomAdvertNumber = RandomClass.Next(AdvertsArrayList.Count);
                            TheLogger.Debug("Attempting advert #" + RandomAdvertNumber.ToString() + " of " + AdvertsArrayList.Count.ToString() + " in total\n");
                            string Advert, Advert2 = "";
                            Advert = (string)AdvertsArrayList[RandomAdvertNumber];
                            ii = 0;
                            for (RandomAdvertNumber = 0; RandomAdvertNumber < Advert.Length; RandomAdvertNumber++)
                            {
                                if (Advert[RandomAdvertNumber] != '\\')
                                {
                                    Advert2 += Advert[RandomAdvertNumber].ToString();
                                    ii++;
                                }
                            }
                            Advert = Advert2;
                            Advert2 = endm;
                            if (Advert2.Length > 50)
                                Advert2 = Advert2.Substring(0, 50);
                            if (Advert.Length + Advert2.Length > 154)
                                Advert = Advert.Substring(0, 154 - Advert2.Length);
//                            Advert += Advert2;
                            //Advert += "[inv/loc/wanted]";
                            TheLogger.Debug("Advert \"" + Advert + "\"\n");
                            TheTCPWrapper.Send(CommandCreator.RAW_TEXT("#jc " + TheMySqlManager.advertchannel(Settings.botid).ToString()));
                            TheTCPWrapper.Send(CommandCreator.RAW_TEXT("@" + Advert));
                            TheTCPWrapper.Send(CommandCreator.RAW_TEXT("#lc " + TheMySqlManager.advertchannel(Settings.botid).ToString()));
                            TheMySqlManager.advertlog("@@" + TheMySqlManager.advertchannel(Settings.botid).ToString() + " " + Advert);
                        }
                    }
                    catch (Exception ex)
                    {
                        TheLogger.ErrorLog("AdvertTimer_Tick:", ex);
                    }
                }
                else
                {
                    TheTCPWrapper.Send(CommandCreator.RAW_TEXT("#jc " + TheMySqlManager.advertchannel(Settings.botid).ToString()));
                    TheTCPWrapper.Send(CommandCreator.RAW_TEXT("@" + str));
                    TheTCPWrapper.Send(CommandCreator.RAW_TEXT("#lc " + TheMySqlManager.advertchannel(Settings.botid).ToString()));
                    TheMySqlManager.advertlog("@@" + TheMySqlManager.advertchannel(Settings.botid).ToString() + " " + str);
                }
                str = "UPDATE bots SET lastadverttime = now() WHERE id = '" + Settings.botid + "' LIMIT 1;";
                TheMySqlManager.raw_sql(str);
            }
        }

        /*
        private void AdvertTimer2_Tick(object sender, ElapsedEventArgs e)
         {
             int x=TheMySqlManager.foodlevel(Settings.botid);
             this.AdvertTimer2.Interval = (121 * 1000);// + RandomClass.Next(0, (60 * 60 * 1000)); ;//m*s*us=1 hour
         }
         */

        private void OnGotConnected(object sender, EventArgs e)
        {
            AdvertTimer.Start();
            //AdvertTimer2.Start();
        }

        private void OnGotDisconnected(object sender, EventArgs e)
        {
            AdvertTimer.Stop();
            //AdvertTimer2.Stop();
        }
    }
}
